package com.bn.commerce.order.purchase;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import atg.commerce.CommerceException;
import atg.commerce.order.CommerceItem;
import atg.commerce.order.Order;
import atg.commerce.pricing.PricingModelHolder;
import atg.commerce.util.PipelineErrorHandler;
import atg.dtm.TransactionDemarcation;
import atg.dtm.TransactionDemarcationException;
import atg.projects.store.order.purchase.StorePurchaseProcessHelper;
import atg.projects.store.profile.StorePropertyManager;
import atg.repository.RepositoryItem;
import atg.userprofiling.PropertyManager;

public class BNPurchaseProcessorHelper extends StorePurchaseProcessHelper {

	public List deleteItems(Order pOrder, String[] pRemovalCommerceIds,
			PricingModelHolder pUserPricingModels, Locale pUserLocale,
			RepositoryItem pProfile, PipelineErrorHandler pErrorHandler,
			Map pExtraParameters) throws CommerceException {
		List deletedSkus = new ArrayList();
		synchronized (pOrder) {
			if ((pRemovalCommerceIds != null)
					&& (pRemovalCommerceIds.length > 0)) {
				TransactionDemarcation td = new TransactionDemarcation();
				boolean rollback = true;
				try {
					td.begin(getTransactionManager(), 3);
					for (int i = 0; i < pRemovalCommerceIds.length; ++i) {
						CommerceItem item = pOrder
								.getCommerceItem(pRemovalCommerceIds[i]);

						deleteItem(pRemovalCommerceIds[i], pOrder);
						deletedSkus.add(item.getCatalogRefId());
						runProcessRepriceOrder(
								getDeleteItemsFromOrderPricingOp(), pOrder,
								pUserPricingModels, pUserLocale, pProfile,
								pExtraParameters, pErrorHandler);

						postDeleteItem(pOrder, item, item.getQuantity(),
								pErrorHandler);
					}

					getOrderManager().updateOrder(pOrder);
					rollback = false;
				} catch (Exception e) {
					Object[] args = { pOrder.getId() };
					throw new CommerceException("hiiiiiiiiiiiiiiiiiiiiiiii", e);
				} finally {
					try {
						td.end(rollback);
					} catch (TransactionDemarcationException tde) {
						throw new CommerceException(tde);
					}
				}
			}
		}

		return deletedSkus;
	}

	/**
	 * Checks if the profile/user is eligible for express checkout
	 *
	 * @return true if the user is eligible for express checkout
	 */
	public boolean isEligibleForExpressCheckout(RepositoryItem profile) {

		boolean isEligibleForExpressCheckout = false;

		// If the user is logged in, validate that all default properties are set
		if (isUserLoggedIn(profile)) {
			isEligibleForExpressCheckout = validateShippingAddressForExpressCheckout(profile) && validateShippingMethodForExpressCheckout(profile) && validateCreditCardForExpressCheckout(profile);
		}

		return isEligibleForExpressCheckout;
	}

	/**
	 * Checks if the user is logged in
	 *
	 * @param profile
	 * @return
	 */
	public boolean isUserLoggedIn(RepositoryItem profile) {

		PropertyManager propertyManager = getStoreOrderTools().getProfileTools().getPropertyManager();
		Integer securityStatus = (Integer) profile.getPropertyValue(propertyManager.getSecurityStatusPropertyName());

		return securityStatus >= propertyManager.getSecurityStatusLogin();
	}

	/**
	 * Validates profile's default shipping address for Express Checkout.
	 *
	 * @param pProfile profile repository item
	 * @return true if profile's default shipping address is valid for Express Checkout
	 */
	public boolean validateShippingAddressForExpressCheckout(RepositoryItem profile) {

		// Return false if default shipping not set
		StorePropertyManager propertyManager = (StorePropertyManager) getStoreOrderTools().getProfileTools().getPropertyManager();
		String shippingAddressPropertyName = propertyManager.getShippingAddressPropertyName();
		String address1PropertyName = propertyManager.getAddressLineOnePropertyName();

		RepositoryItem shippingAddress = (RepositoryItem) profile.getPropertyValue(shippingAddressPropertyName);

		boolean isValidShippingAddress = false;

		if (shippingAddress == null) {
			vlogDebug("User's " + shippingAddressPropertyName + " is null");
			isValidShippingAddress = false;
		} else {
			String address1 = (String) shippingAddress.getPropertyValue(address1PropertyName);

			if (address1 == null || address1.isEmpty()) {
				vlogDebug("User's " + shippingAddressPropertyName + "." + address1PropertyName + " is null");
				isValidShippingAddress = false;
			} else {
				vlogDebug("User's " + shippingAddressPropertyName + "." + address1PropertyName + " is set");
				isValidShippingAddress = true;
			}
		}

		return isValidShippingAddress;
	}


	/**
	 * Validates profile's default credit card for Express Checkout.
	 *
	 * @param pProfile profile repository item
	 * @return true if profile's default credit card is valid for Express Checkout
	 */
	public boolean validateCreditCardForExpressCheckout(RepositoryItem profile) {

		// Return false if default cc not set
		StorePropertyManager propertyManager = (StorePropertyManager) getStoreOrderTools().getProfileTools().getPropertyManager();
		String defaultCreditCardPropertyName = propertyManager.getDefaultCreditCardPropertyName();
		String ccTypePropertyName = propertyManager.getCreditCardTypePropertyName();

		RepositoryItem creditCard = (RepositoryItem) profile.getPropertyValue(defaultCreditCardPropertyName);
		boolean isValidCreditCard = false;

		if (creditCard == null) {
			vlogDebug("User's " + defaultCreditCardPropertyName + " is null");
			isValidCreditCard = false;
		} else {
			String ccType = (String) creditCard.getPropertyValue(ccTypePropertyName);

			if (ccType == null || ccType.isEmpty()) {
				vlogDebug("User's " + defaultCreditCardPropertyName + "." + ccTypePropertyName + " is null");
				isValidCreditCard = false;
			} else {
				vlogDebug("User's " + defaultCreditCardPropertyName + "." + ccTypePropertyName + " is " + ccType);
				isValidCreditCard = true;
			}
		}

		return isValidCreditCard;

	}

	/**
	 * Validates profile's default shipping method for Express Checkout.
	 *
	 * @param pProfile profile repository item
	 * @return true if profile's default shipping method is valid for Express Checkout
	 */
	public boolean validateShippingMethodForExpressCheckout(RepositoryItem profile) {

		// Return false if default shipping method not set

		StorePropertyManager propertyManager = (StorePropertyManager) getStoreOrderTools().getProfileTools().getPropertyManager();
		String defaultShippingMethodPropertyName = propertyManager.getDefaultShippingMethodPropertyName();

		String shippingMethod = (String) profile.getPropertyValue(defaultShippingMethodPropertyName);
		boolean isValidShippingMethod = false;

		if (shippingMethod == null || shippingMethod.isEmpty()) {
			vlogDebug("User's " + defaultShippingMethodPropertyName + " is null");
			isValidShippingMethod = false;
		} else {
			vlogDebug("User's " + defaultShippingMethodPropertyName + " is " + shippingMethod);
			isValidShippingMethod = true;
		}

		return isValidShippingMethod;

	}

}
